//
//  HJAddVC.m
//  project
//
//  Created by hu on 2019/3/21.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJAddVC.h"
#import "YFPublishDongtaiView.h"
#import "YFImagePicker.h"
#import "TZImageManager.h"
#import "YFMapSearchVC.h"

@interface HJAddVC ()

/**
 发布内容的View
 */
@property (nonatomic, strong) YFPublishDongtaiView *publishView;

/**
 布局
 */
@property (nonatomic, strong, nonnull) UIScrollView *scrollView;

@property (nonatomic, strong) UIButton *locationBtn;

@end

@implementation HJAddVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navTitle = @"发布动态";
    [self setupViews];
    self.leftNavImageName = @"back_black_left";
    LKLog(@"videoURL:%@", self.videoURL);
    self.rightNavTitle = @"发布";
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
}

-(void)didClickLeftNavAction {
    if (self.ispush) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupViews {
    [self setupScrollView];
    [self setupPublishView];
}

- (void)setupScrollView {
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    scrollView.contentSize = CGSizeMake(self.view.width, 320);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.clipsToBounds = YES;
    scrollView.bounces = YES;
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    
    YFPublishDongtaiView *publishView = [YFPublishDongtaiView loadFromXib:[YFPublishDongtaiView class]];
    publishView.frame = CGRectMake(0, 0, self.view.width, 320);
    _publishView = publishView;
    _publishView.assets = self.assets;
    
    [self.scrollView addSubview:_publishView];
}

- (void)setupPublishView {
    // 调整 publishView 高度
    @weakify(self)
    self.publishView.updatePublishViewFrameAction = ^(CGFloat height) {
        @strongify(self)
        [UIView animateWithDuration:0.25 animations:^{
            self.publishView.frame = CGRectMake(0, 0, self.view.width, height);
            self.scrollView.contentSize = CGSizeMake(self.publishView.width, height);
            [self.view layoutIfNeeded];
        }];
    };
//    self.publishView.isImage = _dongtaiType == YFDongtaiTypeImages ? YES : NO;
    self.publishView.isImage = NO;
    self.publishView.videoURL = self.videoURL;
    
    if (_dongtaiType == YFDongtaiTypeImages) {
        self.publishView.photos = self.photos;
    }
    
    if (_dongtaiType == YFDongtaiTypeVideo) {
        self.publishView.videoCoverImage = self.videoCoverImage;
    }
    //选择我的位置回调
    self.publishView.locationAction = ^{
         @strongify(self)
        YFMapSearchVC *vc = YFMapSearchVC.new;
        @weakify(self)
        vc.searchCompleted = ^(YFMapSearchModel *model) {
            @strongify(self)
            self.publishView.locationStr = model.POIName;
            LKLog(@"%@", model.POIName);
            //model.POIName;
        };
        [[UIViewController currentViewController].navigationController pushViewController:vc animated:YES];
    };
    // 发布动态回调
    self.publishView.publishAction = ^(NSString * _Nullable dongtai, BOOL isVideo, NSURL * _Nullable videoURL, UIImage * _Nullable videoCoverImage, NSArray<UIImage *> * _Nullable images) {
        @strongify(self)
        if (isVideo) {
            self.videoURL = videoURL;
            self.videoCoverImage = videoCoverImage;
        } else {
            self.photos = [NSArray arrayWithArray:images];
        }
    };
}

/**
 发布网络请求
 */
-(void)didClickRightNavAction {
    if ((!self.videoCoverImage && self.photos.count==0) || (self.publishView.publishTextView.text.length && (!self.videoURL && self.photos.count==0))) {
        [self showErrorHUDWithError:@"心情分享，即刻开始！"];
        return;
    }
    NSString * dongtai = self.publishView.publishTextView.text;
    NSDictionary * params = [NSDictionary dictionary];
    if (dongtai.length) {
        params = @{@"content": dongtai};
    }
    if (self.publishView.isImage) {
        if (params.count>0) {
            [self uploadImages:params images:self.photos];
        }else {
            [self uploadImages:nil images:self.photos];
        }
    } else {
        if (params.count>0) {
            [self uploadVideo:self.videoURL parameters:params videoCoverImages:@[self.videoCoverImage]];
        }else {
            [self uploadVideo:self.videoURL parameters:nil videoCoverImages:@[self.videoCoverImage]];
        }
    }
}

#pragma mark - 网络请求
/**
 发布视频
 @param videoURL 视频本地地址
 @param parameters 附加参数
 */
- (void)uploadVideo:(NSURL *)videoURL parameters:(NSDictionary *)parameters videoCoverImages:(NSArray <UIImage *> *)videoCoverImages {
    
    @weakify(self)
    // 压缩视频
    [YFHud showProgress:@"发布中"];
    [videoURL compressVideoCompletion:^(NSURL * _Nonnull outputURL, BOOL isSuccess) {
        
        @strongify(self)
        NSURL *videoOutputURL;
        if (isSuccess) {
            videoOutputURL = outputURL;
        } else {
            videoOutputURL = videoURL;
        }
        LKLog(@"压缩完成：视频URL%@, 视频Size: %f, 视频时长：%zd", videoOutputURL, videoOutputURL.videoSize, videoOutputURL.videoLength);
        
        // 上传视频和缩略图是否成功，有一个不成功则不成功
        __block BOOL isUploadSuccess = NO;
        __block NSString *videoCoverImageString = @"";
        __block NSString *videoString = @"";
        __block NSURL *videoUploadURL = videoOutputURL;
        
        // 线程调度
        dispatch_group_t group = dispatch_group_create();
        
        // 上传图片
        dispatch_group_enter(group);
        // 上传视频缩略图
        NSString *url = [Api stringByAppendingString:UploadImageApi];
        [HJHttpTool uploadImageWithUrl:url params:nil name:@"multipartFiles" imageArray:videoCoverImages completion:^(NSArray *result, NSError *error) {
            
            // 上传视频缩略图失败
            if (error) { isUploadSuccess = NO; }
            else {
                // 上传视频缩略图成功
                if (result.count != 0) videoCoverImageString = result.firstObject;
                isUploadSuccess = YES;
            }
            LKLog(@"上传视频缩略图%@", isUploadSuccess ? @"成功": @"失败");
            dispatch_group_leave(group);
        }];
        
        // 上传视频
        dispatch_group_enter(group);
        // 上传视频
        NSString *videoURL = [Api stringByAppendingString:UploadFileApi];
        [HJHttpTool UploadFile:videoURL filePath:videoUploadURL name:@"myvideo" param:nil process:^(NSInteger writedBytes, NSInteger totalBytes) {
            LKLog(@"视频上传--写入：%zd 字节， 总共：%zd 字节", writedBytes, totalBytes);
        } success:^(NSDictionary *result) {
            if ([result[@"code"] integerValue] == 200) {
                isUploadSuccess = YES;
                NSString *videoURLString = [NSString stringWithFormat:@"%@", result[@"data"]];
                videoString = videoURLString;
            } else {
                isUploadSuccess = NO;
            }
            LKLog(@"上传视频缩略图%@", isUploadSuccess ? @"成功": @"失败");
            dispatch_group_leave(group);
        } failure:^(NSString *msg) {
            isUploadSuccess = NO;
            LKLog(@"上传视频缩略图%@", isUploadSuccess ? @"成功": @"失败");
            dispatch_group_leave(group);
        }];
        
        // 通知服务器
        @weakify(self)
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            
            LKLog(@"上传视频和视频缩略图%@", isUploadSuccess ? @"成功": @"失败");
            
            if (!isUploadSuccess) {
                [YFHud showError:@"发布失败"];
                return ;
            }
            
            // 装配参数
            NSUInteger duration = videoUploadURL.videoLength;
            NSDictionary *files = @{
                                    @"url":videoString,
                                    @"fileType": @"video",
                                    @"duration": @(duration),
                                    @"thumbnail":videoCoverImageString
                                    };
            NSMutableArray *videoJsonArray = [NSMutableArray arrayWithCapacity:1];
            [videoJsonArray addObject:files];
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:videoJsonArray options:NSJSONWritingPrettyPrinted error:nil];
            NSString *jsonFiles = [[NSString alloc] initWithData:jsonData encoding:(NSUTF8StringEncoding)];
            
            LKLog(@"装配好的视频参数：%@", jsonFiles);
            
            // post 参数
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            if (parameters != nil) {
                [params addEntriesFromDictionary:parameters];
            }
            [params setObject:jsonFiles forKey:@"files"];
            [params setObject:[HJUserManager getUserModel].userId forKey:@"userId"];
            
            LKLog(@"上传视频参数到服务器：%@", params);
            
            NSString *postString = [Api stringByAppendingString:PublishDongtaiApi];
            @strongify(self)
            @weakify(self)
            [HJHttpTool post:postString params:params success:^(HJResponeds *result) {
                @strongify(self)
                [YFHud showSuccessInWindow:@"发布成功" dismissAfter:2];
                if (self.ispush) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                    return;
                }
                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(id result) {
                LKLog(@"动态发布失败：%@", result);
                [YFHud showError:@"发布失败"];
            }];
        });
    }];
}

/**
 发布图片

 @param parameters 附加参数
 @param images 图片数组
 */
- (void)uploadImages:(NSDictionary *)parameters images:(NSArray<UIImage *> *)images {
    
    [YFHud showProgress:@"发布中"];
    @weakify(self)
    // 上传图片
    NSString *url = [Api stringByAppendingString:UploadImageApi];
    [HJHttpTool uploadImageWithUrl:url params:nil name:@"multipartFiles" imageArray:images completion:^(NSArray *result, NSError *error) {
        
        if (error) {
            [YFHud showError:@"发布失败"];
            return ;
        }
        
        LKLog(@"上传图片数组成功");
        LKLog(@"上传图片：%@", result);
        // 装配参数
        NSMutableArray *images = [NSMutableArray arrayWithCapacity:result.count];
        for (int i = 0; i < result.count; i ++) {
            NSString *imageURLString = result[i];
            NSString *fileType = @"image";
            NSDictionary *files = @{
                                    @"url":imageURLString,
                                    @"fileType":fileType,
                                    };
            [images addObject:files];
        }
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:images options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonFiles = [[NSString alloc] initWithData:jsonData encoding:(NSUTF8StringEncoding)];
        
        LKLog(@"图片参数files：%@",jsonFiles);
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        if (parameters != nil) {
            [params addEntriesFromDictionary:parameters];
        }
        [params setObject:jsonFiles forKey:@"files"];
        [params setObject:[HJUserManager getUserModel].userId forKey:@"userId"];
        
        NSString *postURLString = [Api stringByAppendingString:PublishDongtaiApi];
        @strongify(self)
        @weakify(self)
        [HJHttpTool post:postURLString params:params success:^(HJResponeds *result) {
            @strongify(self)
            if (result.isSuccess) {
                [YFHud showSuccessInWindow:@"发布成功" dismissAfter:2];
                if (self.ispush) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                    return;
                }
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [YFHud showError:@"发布失败"];
            }
        } failure:^(id result) {
             [YFHud showError:@"发布失败"];
        }];
    }];
}

@end
